﻿

#region Using Statements

using UnityEngine;
using System.Collections.Generic;

#endregion


/// <summary>
/// 
/// </summary>
public class PlatformMovement : ObjectScript
{

    #region Members

    public float walkForce = 100.0f;

    public float jumpForce = 500.0f;

    public float airForce { get { return airForceFactor * walkForce; } }
    public float airForceFactor = 0.5f;

    public float groundedDrag = 0.999f;

    public float inputMovement { get; set; }
    public bool inputJump { get; set; }
    public bool hasControl { get; set; }
    public Vector3 lookLocation { get; set; }

    public bool isGrounded { get { return Physics.Raycast(transform.position, Vector3.down, circle.radius * (1 + RayEpsilon)); } }
    public Vector3 look;

    #endregion


    #region Init

	/// <summary>
    /// 
    /// </summary>
    protected virtual void Awake()
    {
        hasControl = true;
    }


    /// <summary>
    /// 
    /// </summary>
    protected virtual void Start()
    {

    }

    #endregion


    #region Update

    /// <summary>
    /// 
    /// </summary>
    protected virtual void Update()
    {
        // look towards look location
        Vector3 diff = lookLocation - transform.position;
        if ( (diff.x > 0.0f) ^ (transform.localScale.x > 0.0f) )
            transform.localScale = new Vector3(transform.localScale.x * -1.0f, transform.localScale.y, transform.localScale.z);
    }


    /// <summary>
    /// 
    /// </summary>
    protected virtual void FixedUpdate()
    {
        // perform raycast only once
        bool grounded = isGrounded;

        // calc force
        float force = (grounded && hasControl) ? walkForce : airForce;

        // add input x force
        rigidbody2D.AddForce(inputMovement * Vector2.right * force * Time.deltaTime);

        // do jumping
        if (isGrounded && inputJump)
            rigidbody2D.AddForce(jumpForce * Vector2.up);

        // keep guy upright if he's got control
        if (hasControl)
            transform.rotation = Quaternion.identity;

        // apply x, y damping
        if (grounded)
            rigidbody2D.velocity *= Util.DampingCoefficient(groundedDrag);
    }

    #endregion

}